package com.carserver.controller;

import cn.hutool.json.JSONObject;
import com.carserver.common.Result;
import com.carserver.pojo.Goods;
import com.carserver.service.GoodsDao;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Resource
    GoodsDao dao;

    @GetMapping
    public Result findall(){
        List<Goods> all = dao.findAll();
        System.out.println(all);
        return Result.success(all);
    }
    @PostMapping("/save")
    public Result save(@RequestBody Goods goods){
        dao.save(goods);
        return Result.success(goods);
    }
    @DeleteMapping("/{id}")
    public Result deleteGoods(@PathVariable("id") Integer id){
        dao.deleteById(id);
        return Result.success("删除成功:"+id);
    }

    @GetMapping("/number/{carNumber}")
    //根据零配件编号获取数量
    public Result getNumberByCarNumber(@PathVariable String carNumber){
        Goods numByCarNumber = dao.getNumByCarNumber(carNumber);
        return Result.success(numByCarNumber);
    }

    @GetMapping("/get_all_number")
    public Result getAllNumber (){
        JSONObject jsonObject=new JSONObject();
        List<Goods> l=dao.findAll();
        for (int i=0;i<l.size();i++){
            jsonObject.set(l.get(i).getCarNumber(),l.get(i).getNumber());
        }

        return Result.success(jsonObject);
    }
//修改货物缺货，剩余数
    @GetMapping("/change_number/{carNumber}/{number}/{sub_number}")
    public Result changeNumberByCarNumber(@PathVariable String carNumber,@PathVariable Integer number,@PathVariable Integer sub_number){
        Goods d=dao.getNumByCarNumber(carNumber);
        d.setNumber(number);
        d.setSub_number(sub_number);
        dao.save(d);
        return Result.success(d);
    }

}
